<?php

namespace addons\epay\controller;

use addons\epay\library\Service;
use think\addons\Controller;
use think\Log;
use think\Db;

/**
 * API接口控制器
 *
 * @package addons\epay\controller
 */
class Api extends Controller {

    protected $config = [];

    public function _initialize() {
        parent::_initialize();
    }

    /**
     * 默认方法
     */
    public function index() {
        $this->error();
    }

    /**
     * 支付成功回调
     */
    public function notify() {
        $type = $this->request->param('type');
        $pay = Service::checkNotify($type);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        $data = $pay->verify(); // 是的，验签就这么简单！
        $orderInfo = Db::name('order')->where(array('order_no' => $data['out_trade_no']))->find();

        if ($orderInfo['status'] != 0) {
            echo $pay->success();
            return;
        }

        Db::startTrans();
        try {

            $total_price = number_format($data['total_fee'] / 100, 2);
            // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
            $saveData['pay_no'] = $data['transaction_id'];
            $saveData['pay_at'] = date('Y-m-d H:i:s');
            $saveData['pay_price'] = $total_price;
            $saveData['is_pay'] = 1;
            $saveData['status'] = 10;

            $res = Db::name('order')->where(array('order_no' => $data['out_trade_no']))->update($saveData);
            if ($orderInfo['type'] == 10) {
                //充值

                $wallet_info = Db::name('wallet')->where(array('user_id' => $orderInfo['user_id']))->find();

                $give_amount = $orderInfo['give_price'];

                $cashData['balance'] = $wallet_info['balance'] + $total_price;
                $giveData = [];
                Db::name('wallet')->where(array('user_id' => $orderInfo['user_id']))->setInc('cash_amount', $total_price);

                if ($give_amount > 0) {
                    $giveData['balance'] = $wallet_info['balance'] + $total_price + $give_amount;
                    Db::name('wallet')->where(array('user_id' => $orderInfo['user_id']))->setInc('give_amount', $give_amount);
                }
                Db::name('wallet')->where(array('user_id' => $orderInfo['user_id']))->setInc('balance', $total_price + $give_amount);

                $cashData['wallet_id'] = $wallet_info['wallet_id'];
                $cashData['change_amount'] = $total_price;
                $cashData['change_matters'] = 1;
                $cashData['order_id'] = $orderInfo['order_id'];

                Db::name('wallet_log')->insert($cashData);

                if ($giveData) {
                    $giveData['change_amount'] = $give_amount;
                    $giveData['wallet_id'] = $wallet_info['wallet_id'];
                    $giveData['change_matters'] = 2;
                    $giveData['order_id'] = $orderInfo['order_id'];

                    Db::name('wallet_log')->insert($giveData);
                }
            } else if ($orderInfo['type'] == 1) {
                //赠送积分
                $zengsong_num = $orderInfo['give_score'];

                if ($zengsong_num > 0) {
                    $user_info = Db::name('users')->where(['user_id' => $orderInfo['user_id']])->find();
                    Db::name('users')->where(['user_id' => $orderInfo['user_id']])->setInc('score', $zengsong_num);

                    $score_log['change_amount'] = $zengsong_num;
                    $score_log['change_matters'] = 1;
                    $score_log['change_type'] = 0;
                    $score_log['user_id'] = $orderInfo['user_id'];
                    $score_log['order_id'] = $orderInfo['order_id'];
                    $score_log['balance'] = $user_info['score'] + $zengsong_num;

                    Db::name('score_log')->insert($score_log);
                }

                //更新小区商品销量
                $order_goods_list = db('order_goods')->where('order_id', $orderInfo['order_id'])->select();

                if ($order_goods_list) {
                    $user_box_info = Db::name('user_box')
                            ->where(['user_box_id' => $orderInfo['user_box_id'], 'status' => 1])
                            ->find();
                    foreach ($order_goods_list as $row) {
                        db('house_goods')->where('goods_id', $row['goods_id'])->where('house_id', $user_box_info['quarters_id'])->setInc('sale_num', $row['buy_num']);
                    }
                }

                //领取满额优惠券
                $coupon_info = db('coupon')->where('receive_type', 2)->where('status', 1)->where('receive_type', '<=', $total_price)->order('receive_conf')->find();

                $coupon_count = db('user_coupon')->where('user_id', $orderInfo['user_id'])->where('coupon_id', $coupon_info['coupon_id'])->count();

                if ($coupon_count < $coupon_info['receive_num']) {
                    receiveCoupon($orderInfo['user_id'], $coupon_info['coupon_id']);
                }
            } else if ($orderInfo['type'] == 2) {
                $bhData['status'] = 1;

                $res = Db::name('order')->where(array('order_no' => $data['out_trade_no']))->update($bhData);
            }
            echo $pay->success();
            Db::commit();
            //下面这句必须要执行,且在此之前不能有任何输出
            return;
        } catch (Exception $ex) {
            Db::rollback();
        }
    }

    /**
     * 支付成功返回
     */
    public function returnx() {
        $type = $this->request->param('type');
        $result = Service::checkReturn($type);
        if (!$result) {
            $this->error('签名错误');
        }
        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("恭喜你！支付成功!", addon_url("epay/index/index"));

        return;
    }

}
